<template>
  <div class="search-container">
    <el-empty
        v-if="showEmpty"
        :description="emptyText"
        class="empty-container"
    />

    <div v-else class="card-grid">
      <el-card
          v-for="item in articles"
          :key="item.id"
          class="article-card"
          shadow="hover"
      >
        <div class="card-header">
          <img
              :src="item.pic"
              alt="文章封面"
              class="cover-image"
              @click="toArticle(item.id)"
          >
        </div>

        <div class="card-body">
          <el-tooltip :content="item.title" placement="top">
            <h3 class="article-title">
              {{ truncateText(item.title, 22) }}
            </h3>
          </el-tooltip>

          <div class="meta-container">
            <el-tag
                class="type-tag"
                effect="plain"
                :color="getTypeColor(item.articleType)"
            >
              {{ showDictUtil(item.articleType, dictData) }}
            </el-tag>

            <div class="meta-info">
              <span class="author">
                <el-icon><User /></el-icon>
                {{ item.user.nickName }}
              </span>
              <span class="date">
                <el-icon><Clock /></el-icon>
                {{ parseTime(item.createTime, '{y}-{m}-{d}') }}
              </span>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Star, User, Clock } from '@element-plus/icons-vue'
import {getDict} from "@/api/common.js";
import {getSearchArticleApi} from "@/api/articleApi.js";
import {parseTime} from "../../tool/utils.js";
import {showDictUtil} from "../../tool/commonFun.js";

// 响应式数据
const route = useRoute()
const router = useRouter()
const searchKeyword = ref(route.query.input || '')
const articles = ref([])
const dictData = ref([])
const showEmpty = ref(true)
const emptyText = ref(`"${searchKeyword.value}" 的搜索结果为空`)

// 初始化
onMounted(async () => {
  await Promise.all([fetchDictData(), searchArticles()])
})

// 获取字典数据
const fetchDictData = async () => {
  try {
    const res = await getDict({ value: 'wz_lx' })
    dictData.value = res.data[0].child
  } catch (error) {
    ElMessage.error('获取分类数据失败')
  }
}

// 搜索文章
const searchArticles = async () => {
  try {
    const res = await getSearchArticleApi(searchKeyword.value)
    articles.value = res.data
    showEmpty.value = articles.value.length === 0
  } catch (error) {
    ElMessage.error('搜索失败，请稍后重试')
  }
}


// 跳转文章详情
const toArticle = (id) => {
  router.push(`/health/article/${id}`)
}

// 工具函数
const truncateText = (text, length) => {
  return text.length > length ? text.slice(0, length) + '...' : text
}

const getTypeColor = (typeValue) => {
  const type = dictData.value.find(item => item.value === typeValue)
  return type?.color || '#dceff9'
}
</script>

<style scoped>
.search-container {
  margin: 24px auto;
  padding: 0 20px;
}

.empty-container {
  margin-top: 100px;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  padding: 16px 0;
}

.article-card {
  position: relative;
  transition: transform 0.3s ease;
  border-radius: 12px;
}

.article-card:hover {
  transform: translateY(-4px);
}

.card-header {
  position: relative;
  border-radius: 12px 12px 0 0;
  overflow: hidden;
}

.cover-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.cover-image:hover {
  transform: scale(1.05);
}



.card-body {
  padding: 16px;
}

.article-title {
  margin: 0 0 12px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  height: 44px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.meta-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.type-tag {
  align-self: flex-start;
  font-size: 12px;
  padding: 4px 8px;
  border: none;
}

.meta-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

.meta-info span {
  display: flex;
  align-items: center;
  gap: 4px;
}

@media (max-width: 768px) {
  .card-grid {
    grid-template-columns: 1fr;
  }

  .search-container {
    padding: 0 12px;
  }

  .cover-image {
    height: 160px;
  }
}
</style>